﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using FoxCommerce.MVC.Domain.Entities;
using FoxCommerce.MVC.Data.Infrastructure;

namespace FoxCommerce.MVC.Data.Repositories
{
    public class UserRepository : EntityRepository<User>, IUserRepository
    {
        public UserRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {
        }
        public void AssignRole(string userName, List<string> roleNames)
        {
            var user = this.FindUser(userName);
            user.Roles.Clear();
            foreach (string roleName in roleNames)
            {
                var role = this.DataContext.Roles.Find(roleName);
                user.Roles.Add(role);
            }

            this.DataContext.Users.Attach(user);
            this.DataContext.Entry(user).State = EntityState.Modified;
        }

        public User FindUser(string userName)
        {
            return DataContext.Users.Where(z => z.UserName == userName).SingleOrDefault();
        }

    }

    public interface IUserRepository : IRepositoryBase<User>
    {
        void AssignRole(string userName, List<string> roleName);
        User FindUser(string userName);
    }
}
